//
// Created by Asus on 2025/6/2.
//

#include <iostream>
#include <map>
#include <bits/ostream.tcc>
using namespace std;

void printMap(map<int, int> &m) {
    for (auto it = m.begin(); it != m.end(); it++) {
		cout << "key = " << it->first << " value = " << it->second << endl;
    }
    cout << endl;
}

void demo01() {
    map<int, int> m;
    pair<map<int,int>::iterator, bool> ret = m.insert(make_pair(2, 2));
    cout << ret.first->first << endl;
    cout << ret.first->second << endl;
    cout << ret.second << endl;
    m.insert(pair<int, int>(2, 20));
    m.insert(pair<int, int>(3, 30));
    printMap(m);
    map<int, int>m2(m); //拷贝构造
    printMap(m2);
    map<int, int>m3;
    m3 = m2; //赋值
    printMap(m3);
}

void demo02() {
    map<int, int>m;
    m.insert(pair<int, int>(1, 10));
    m.insert(pair<int, int>(2, 20));
    m.insert(pair<int, int>(3, 30));
    if (m.empty())
    {
        cout << "m为空" << endl;
    }
    else
    {
        cout << "m不为空" << endl;
        cout << "m的大小为： " << m.size() << endl;
    }

    map<int, int>m2;
    m2.insert(pair<int, int>(4, 100));
    m2.insert(pair<int, int>(5, 200));
    m2.insert(pair<int, int>(6, 300));
    m2.insert(pair<int, int>(7, 300));

    cout << "交换前" << endl;
    printMap(m);
    printMap(m2);

    cout << "交换后" << endl;
    m.swap(m2);
    printMap(m);
    printMap(m2);
}

void demo03() {
    map<int, int>m;
    m.insert(pair<int, int>(1, 10));
    m.insert(make_pair(2, 20));
    m.insert(map<int, int>::value_type(3, 30));
    m[4] = 100;
    printMap(m);

    m.erase(m.begin());
    printMap(m);

    m.clear();
    printMap(m);
}

void demo04() {
    map<int, int>m;
    m.insert(pair<int, int>(1, 10));
    m.insert(pair<int, int>(2, 20));
    m.insert(pair<int, int>(3, 30));

    m.find(3)->second = 100;
    printMap(m);

    map<int, int>::iterator pos = m.find(3);
    if (pos != m.end()) {
        cout << "找到了元素 key = " << (*pos).first << " value = " << (*pos).second << endl;
    }	else
    {
        cout << "未找到元素" << endl;
    }
    //统计
    int num = m.count(3);
    cout << "num = " << num << endl;
}


class MyCompare {
public:
    bool operator()(int v1, int v2) const{
        return v1 > v2;
    }
};

void demo05() {
    //默认从小到大排序
    //利用仿函数实现从大到小排序
    map<int, int, MyCompare> m;
    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 20));
    m.insert(make_pair(3, 30));
    m.insert(make_pair(4, 40));
    m.insert(make_pair(5, 50));

    for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++) {
        cout << "key:" << it->first << " value:" << it->second << endl;
    }
}

int main(int argc, char *argv[]) {
    // demo01();
    // demo02();
    // demo03();
    // demo04();
    demo05();
    return 0;
}
